Page({
  data: {
    keyword: '',
    searchResults: [],
    searchHistory: [],
    banners: [
      {
        imageUrl: 'https://images.unsplash.com/photo-1517694712202-14dd9538aa97?ixlib=rb-4.0.3&auto=format&fit=crop&w=1000&q=80',
        title: '编程世界',
        subtitle: '探索代码的魅力'
      },
      {
        imageUrl: 'https://images.unsplash.com/photo-1550439062-609e1531270e?ixlib=rb-4.0.3&auto=format&fit=crop&w=1000&q=80',
        title: '人工智能',
        subtitle: '开启智能新时代'
      },
      {
        imageUrl: 'https://images.unsplash.com/photo-1526374965328-7f61d4dc18c5?ixlib=rb-4.0.3&auto=format&fit=crop&w=1000&q=80',
        title: '算法之美',
        subtitle: '解锁技术的奥秘'
      }
    ],
    hotSearches: [],
    loading: false,
    error: null,
    showToast: false,
    toastTitle: '',
    toastDuration: 2000
  },

  onLoad() {
    // 从本地存储加载搜索历史
    const history = wx.getStorageSync('searchHistory') || [];
    this.setData({ searchHistory: history });

    // 获取热门搜索
    this.fetchHotTopics();
  },

  // 处理401错误
  handleUnauthorized() {
    getApp().handleUnauthorized();
  },

  // 获取热门搜索
  fetchHotTopics() {
    // 检查内存中是否有缓存
    const app = getApp();
    if (app.globalData && app.globalData.hotTopics) {
      const { data, timestamp } = app.globalData.hotTopics;
      // 检查缓存是否在同一天
      const today = new Date().toDateString();
      const cacheDate = new Date(timestamp).toDateString();
      if (today === cacheDate) {
        this.setData({ hotSearches: data });
        return;
      }
    }

    wx.request({
      url: 'https://www.haoyuming.online/api/user/search/hot-topics',
      method: 'GET',
      success: (res) => {
        console.log('热门搜索响应：', res.data);
        if (res.data.code === 200) {
          const hotTopics = res.data.data;
          // 保存到内存中
          if (getApp().globalData) {
            getApp().globalData.hotTopics = {
              data: hotTopics,
              timestamp: new Date().getTime()
            };
          }
          this.setData({ hotSearches: hotTopics });
        } else {
          this.showCustomToast(res.data.msg || '获取热门搜索失败');
        }
      },
      fail: (err) => {
        console.error('获取热门搜索失败：', err);
        this.showCustomToast('网络错误，请稍后重试');
      }
    });
  },

  // 返回上一页
  onBackTap() {
    wx.navigateBack();
  },

  // 输入关键词
  onKeywordInput(e) {
    this.setData({
      keyword: e.detail.value.trim()
    });
  },

  // 执行搜索
  onSearch() {
    const { keyword } = this.data;
    if (!keyword) {
      this.showCustomToast('请输入搜索关键词');
      return;
    }

    // 保存到搜索历史
    this.saveSearchHistory(keyword);

    // 开始搜索
    this.setData({ loading: true, error: null });

    wx.request({
      url: 'https://www.haoyuming.online/api/user/article/search',
      method: 'GET',
      data: { keyword },
      success: (res) => {
        console.log('搜索响应：', res.data);
        if (res.data.code === 200) {
          // 处理搜索结果
          const results = res.data.data.map(item => ({
            ...item,
            // 高亮处理标题
            highlightedTitle: this.highlightKeyword(item.title, keyword),
            // 高亮处理内容片段
            highlightedSnippet: item.contentSnippet ? 
              this.highlightKeyword(item.contentSnippet, keyword) : '',
            // 格式化时间
            createTime: this.formatDate(item.createTime)
          }));

          this.setData({
            searchResults: results,
            loading: false,
            error: null
          });
        } else {
          this.setData({
            error: res.data.message || '搜索失败',
            loading: false
          });
        }
      },
      fail: (err) => {
        console.error('搜索失败：', err);
        this.setData({
          error: '网络错误，请稍后重试',
          loading: false
        });
      }
    });
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    let history = this.data.searchHistory;
    // 移除重复的关键词
    history = history.filter(item => item !== keyword);
    // 添加到开头
    history.unshift(keyword);
    // 最多保存10条
    history = history.slice(0, 10);
    
    this.setData({ searchHistory: history });
    wx.setStorageSync('searchHistory', history);
  },

  // 清空搜索历史
  clearHistory() {
    this.setData({ searchHistory: [] });
    wx.removeStorageSync('searchHistory');
    this.showCustomToast('搜索历史已清空');
  },

  // 点击历史记录
  onHistoryTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({ keyword }, () => {
      this.onSearch();
    });
  },

  // 点击热门搜索
  onHotTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({ keyword }, () => {
      this.onSearch();
    });
  },

  // 点击搜索结果
  onResultTap(e) {
    const article = e.currentTarget.dataset.article;
    wx.navigateTo({
      url: `/pages/article-detail/article-detail?id=${article.id}`
    });
  },

  // 高亮关键词
  highlightKeyword(text, keyword) {
    if (!text || !keyword) return text;
    const reg = new RegExp(keyword, 'gi');
    return text.replace(reg, match => `<span style="color: #4CAF50;">${match}</span>`);
  },

  // 格式化日期
  formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  },

  // 显示自定义提示
  showCustomToast(title, duration = 2000) {
    this.setData({
      showToast: true,
      toastTitle: title,
      toastDuration: duration
    });
  },

  // 提示隐藏回调
  onToastHide() {
    this.setData({
      showToast: false,
      toastTitle: ''
    });
  }
});
